package com.bxd.baodan.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.bxd.baodan.app.SharedPreferanceKey;
import com.bxd.baodan.item.DeviceItem;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {
	 public static String getAppMetaData(Context ctx, String key) {
	        if (ctx == null || TextUtils.isEmpty(key)) {
	            return null;
	        }
	        String resultData = null;
	        try {
	            PackageManager packageManager = ctx.getPackageManager();
	            if (packageManager != null) {
	                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
	                if (applicationInfo != null) {
	                    if (applicationInfo.metaData != null) {
	                        resultData = applicationInfo.metaData.getString(key);
	                    }
	                }

	            }
	        } catch (PackageManager.NameNotFoundException e) {
	            e.printStackTrace();
	        }

	        return resultData;
	    }
	/*
	 * 判断手机中是否安装了某一应用程序
	 */
	public static boolean isAvilible(Context context, String packageName){
        final PackageManager packageManager = context.getPackageManager();//获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);//获取所有已安装程序的包信息
        List<String> pName = new ArrayList<String>();//用于存储所有已安装程序的包名
       //从pinfo中将包名字逐一取出，压入pName list中
            if(pinfo != null){
            for(int i = 0; i < pinfo.size(); i++){
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);//判断pName中是否有目标程序的包名，有TRUE，没有FALSE
  }
	//判断是否为勿扰模式
	public static boolean isNotDisturbOn() {
		if (SpUtil.getInstance().getBoolean(
				SharedPreferanceKey.NO_DISTURB_STYLE)) {
			long startTime = SpUtil.getInstance().getLong(
					SharedPreferanceKey.NO_DISTURB_START);
			long endTime = SpUtil.getInstance().getLong(
					SharedPreferanceKey.NO_DISTURB_END);
			try {
				Calendar cal1 = Calendar.getInstance();
				Calendar cal2 = Calendar.getInstance();
				Calendar cal3 = Calendar.getInstance();
				cal1.setTimeInMillis(startTime);
				cal2.setTimeInMillis(endTime);
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				cal1.setTime(sdf.parse(sdf.format(new Date(startTime))));
				cal2.setTime(sdf.parse(sdf.format(new Date(endTime))));
				cal3.setTime(sdf.parse(sdf.format(new Date())));
				int h1 = cal1.get(Calendar.HOUR_OF_DAY);
				int h2 = cal2.get(Calendar.HOUR_OF_DAY);
				int h3 = cal3.get(Calendar.HOUR_OF_DAY);
				if (h3 >= h1 && h3 <= h2) {
					return true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return false;
	}
	/**
	 * 更多分享方式
	 */
	public static void shareMsg(String activityTitle, String msgTitle, String msgText,
			String imgPath, Activity content) {
		Intent intent = new Intent(Intent.ACTION_SEND);
		if (imgPath == null || imgPath.equals("")) {
			intent.setType("text/plain"); // 纯文本
		} else {
			File f = new File(imgPath);
			if (f != null && f.exists() && f.isFile()) {
			}
			intent.setType("image/*");
			Uri u = Uri.fromFile(f);
			intent.putExtra(Intent.EXTRA_STREAM, u);
		}
		intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
		intent.putExtra(Intent.EXTRA_TEXT, msgText);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		content.startActivity(Intent.createChooser(intent, activityTitle));
	}
	/*
	 * 得到格式化的时间
	 */
	public static String getFormatDate(String paramDate) {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
		           date = format1.parse(paramDate);
		} catch (ParseException e) {
		           e.printStackTrace();
		}

		   return format1.format(date);
		}
	/**
	 * 获取本机号码
	 * */
	public static String getPhoneNo(Context context) {
		TelephonyManager phoneMgr=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
		return phoneMgr.getLine1Number();
	}
	/**
	 * 获取设备的唯一标识码IMEI
	 */
   public static String getDeciveId(Context context) {
	   TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
	   String   gsm = tm.getDeviceId();
	   if (gsm != null && !"".equals(gsm)) {
		   return gsm;
	   }
	   return tm.getSubscriberId();
   }
   /**
    * 获取设备型号（MD5加密后）
    */
   public static String getDeviceType() {
	   return Build.MODEL;
   }
   /**
    * 获取系统版本号（MD5加密后）
    */
   public static String getSystemVersionNum() {
	   return Build.VERSION.RELEASE;
   }
   /**
    * 得到当前的手机网络类型（MD5加密后）
    *
    * @param context
    * @return
    */
   public static String getCurrentNetType(Context context) {
       String type = "";
       ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
       NetworkInfo info = cm.getActiveNetworkInfo();
       if (info == null) {
           type = "null";
       } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
           type = "wifi";
       } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
           int subType = info.getSubtype();
           if (subType == TelephonyManager.NETWORK_TYPE_CDMA || subType == TelephonyManager.NETWORK_TYPE_GPRS
                   || subType == TelephonyManager.NETWORK_TYPE_EDGE) {
               type = "2g";
           } else if (subType == TelephonyManager.NETWORK_TYPE_UMTS || subType == TelephonyManager.NETWORK_TYPE_HSDPA
                   || subType == TelephonyManager.NETWORK_TYPE_EVDO_A || subType == TelephonyManager.NETWORK_TYPE_EVDO_0
                   || subType == TelephonyManager.NETWORK_TYPE_EVDO_B) {
               type = "3g";
           } else if (subType == TelephonyManager.NETWORK_TYPE_LTE) {// LTE是3g到4g的过渡，是3.9G的全球标准
               type = "4g";
           }
       }
       return type;
   }
   /**
    * 对设备型号等信息进行加密处理
    * @param context
    * @return
    */
   public static String deviceJson(Context context) {
	   DeviceItem item = new DeviceItem();
	   item.setDevicetype(getDeviceType());
	   item.setSystem_version(getSystemVersionNum());
	   item.setNettype(getCurrentNetType(context));
	   String jsonStr = new Gson().toJson(item, DeviceItem.class);
	   try {
			return  URLEncoder.encode(DesUtil.encode(jsonStr), "UTF-8");
	   } catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
	   }

   }
   /**
    * 得到提取数字的list
    * @param string
    * @return
    */
   public static ArrayList getNumIndexOf (String string) {
	   ArrayList<String> list = new ArrayList<String>();
	   String str = "";
	   String regex = "\\d*";
	   Pattern p = Pattern.compile(regex);
	   Matcher m = p.matcher(string);
	   while (m.find()) {
		   str = m.group();
		   if (!"".equals(str)) {
			   list.add(str);
		   }
	   }
	   return list;
   }

	public static boolean isMobileNO(String mobiles){
		Pattern p = null;
		Matcher m = null;
		boolean b = false;
		p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号
		m = p.matcher(mobiles);
		b = m.matches();
		return b;
	}
   /**
    * 返回保险代理人人数
    */
   public static String returnAgentNum(String agentNum) {
	   LogUtil.e("----agentNum----" + agentNum);
	   LogUtil.e("----length----" + agentNum.length());
	   String num = agentNum;
	   String str = agentNum.substring(0, 1);
	   LogUtil.e("----str----" + str);
	   if (agentNum.length() >= 5 && agentNum.length() < 6) {
		   switch (Integer.parseInt(str)) {
		case 1:
			num = "一万多";
			break;
		case 2:
			num = "两万多";
			break;
		case 3:
			num = "三万多";
			break;
		case 4:
			num = "四万多";
			break;
		case 5:
			num = "五万多";
			break;
		case 6:
			num = "六万多";
			break;
		case 7:
			num = "七万多";
			break;
		case 8:
			num = "八万多";
			break;
		case 9:
			num = "九万多";
			break;

		default:
			break;
		}
	   } else if (agentNum.length() < 5) {
		   num = "近一万";
	   }
	   return num;
   }
}
